package hhm.android.my

import android.os.Bundle
import android.widget.FrameLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import hhm.android.library.bus.Bus
import siau.android.base.HttpHelper
import siau.android.base.MESSAGE_ROUTER
import siau.android.base.SBApplication
import siau.android.base.SBBaseActivity
import siau.android.http.model.MessageListModel
import siau.android.http.model.PageNumAndPageSizeRequest
import siau.android.library.KeyString
import java.util.ArrayList

@Route(path = MESSAGE_ROUTER)
class MessageActivity : SBBaseActivity() {

    var pageNo = 1
    var pageSize = 10
    private lateinit var srl: SmartRefreshLayout
    private lateinit var recyclerView: RecyclerView
    private lateinit var fl: FrameLayout
    private lateinit var adapter: MessageListAdapter
    val list = ArrayList<MessageListModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        setContentView(R.layout.activity_message)
        initTitle(getString(R.string.message))

        srl = findViewById(R.id.activity_message_srl)!!
        recyclerView = findViewById(R.id.activity_message_recycler)
        fl = findViewById(R.id.activity_message_fl)

        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = MessageListAdapter(this, list)
        recyclerView.adapter = adapter

        srl.setOnRefreshListener {
            pageNo = 1
            srl.setEnableLoadMore(true)
            getData()
        }
        srl.setOnLoadMoreListener {
            pageNo++
            getData()
        }

        getData()
    }

    private fun getData() {
        val b = PageNumAndPageSizeRequest(pageNo, pageSize)
        HttpHelper().getMessageList(b)?.subscribe({
            if (pageNo == 1) {
                srl.finishRefresh()
                if (it.list.size == 0) {
                    showNoDataView()
                } else {
                    removeLoadingFragment()
                    adapter.setData(it.list)
                }
            } else {
                removeLoadingFragment()
                srl.finishLoadMore()
                adapter.addData(it.list)
            }
            if (adapter.list.size == it.total) {
                srl.setEnableLoadMore(false)
            }
            SBApplication.userData.unreadCount = calculateUnReadNUm()
        }, {
            srl.finishRefresh()
            srl.finishLoadMore()
            removeLoadingFragment()
            showToast(it.message)
        })
    }

    private fun calculateUnReadNUm(): Int {
        var count = 0

        adapter.list.forEach {
            count += it.unreadCount
        }

        return count
    }


}